<?php
declare (strict_types=1);

namespace app\callback\controller;

use app\admin\model\base\User;
use app\admin\model\base\UserOfficial;
use app\BaseController;
use app\Request;
use platform\LvBaoPlatform;
use think\facade\Log;

/**
 * 绿葆平台
 */
class LvBao extends BaseController
{

    /**
     * 接收回调信息
     * @param Request $request
     * @return string
     */
    public function lvBaoAfterNotify(Request $request): string
    {
        $post_data = file_get_contents("php://input");
        if (!$post_data) {
            $post_data = $request->all();
        }
        $post_data = is_array($post_data) ? $post_data : json_decode($post_data, true);
        //处理完成回调金额
        if (
            isset($post_data['msgType']) and
            isset($post_data['bidPrice']) and
            isset($post_data['authOpenId']) and
            isset($post_data['wxAppId']) and
            $post_data['msgType'] == 'event'
        ) {
            //计算签名
            $post_signature = $post_data['signature'];
            unset($post_data['signature']);
            $LvBao = new LvBaoPlatform();
            $signature = secureSignature($post_data, $LvBao->appSecret);
            if ($post_signature != $signature) {
                Log::write($post_data, '绿葆平台回调签名错误');
                return 'success';
            }
            //获取用户ID
            $user_id = User::where(['uuid' => $post_data['authOpenId']])->value('id');
            if (!$user_id) {
                Log::write($post_data, '绿葆平台回调用户不存在');
                return 'success';
            }
            //记录数据库
            $data = [
                'subscribe' => 1,
                'bid_price' => floatval($post_data['bidPrice']) / 100,
            ];
            $where = [
                'user_id' => $user_id,
                'appid' => $post_data['wxAppId'],
                'third_id' => 4,
            ];
            UserOfficial::update($data, $where);
        }
        return 'success';
    }


}
